package com.jwthhealth_pub.wristband.bloodpressure.fragment;


import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.jwthhealth_pub.R;
import com.jwthhealth_pub.old.api.ApiHelper;
import com.jwthhealth_pub.old.sign.model.LoginModel;
import com.jwthhealth_pub.utils.Contas;
import com.jwthhealth_pub.utils.TimeUtil;
import com.jwthhealth_pub.wristband.bloodpressure.bean.BloodYearBean;
import com.jwthhealth_pub.wristband.newbloodpressure.utils.MyAxisValueFormatter;
import com.jwthhealth_pub.wristband.newbloodpressure.utils.XYMarkerView;
import com.jwthhealth_pub.wristband.steps.adapter.MyStepsViewPagerAdapter;
import com.jwthhealth_pub.wristband.steps.utils.DateUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

//http://blog.csdn.net/ww897532167/article/details/74171294     Android图表控件MPAndroidChart—的使用
public class FragmentBloodPressureYear extends Fragment implements
        ViewPager.OnPageChangeListener{
    @BindView(R.id.customBarChart)
    LinearLayout customBarChart;
    @BindView(R.id.tv_typeDate)
    TextView tv_typeDate;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.btn_left)
    Button btn_left;
    @BindView(R.id.btn_right)
    Button btn_right;
    @BindView(R.id.tv_bottom_title)
    TextView tv_bottom_title;  //下面文字提示
    @BindView(R.id.tv_sbp_hight)

    TextView tv_sbp_hight;  //收缩压最高
    @BindView(R.id.tv_sbp_low)
    TextView tv_sbp_low;  //收缩压最低
    @BindView(R.id.tv_sbp_avg)
    TextView tv_sbp_avg;  //收缩压平均

    @BindView(R.id.tv_dbp_hight)
    TextView tv_dbp_hight;  //舒张压最高
    @BindView(R.id.tv_dbp_low)
    TextView tv_dbp_low;  //舒张压最低
    @BindView(R.id.tv_dbp_avg)
    TextView tv_dbp_avg;  //舒张压平均


    BarChart barChart;
    private int postion = 0;
    private int sumData;
    int pon;
    List<BloodYearBean.DataBean> bloodList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_booldpressure_base, container, false);
        ButterKnife.bind(this, view);
        initData();
        return view;

    }

    private void initData() {
        String uid= "";
        String token= "";
        LoginModel.DataBean userinfoModel = Contas.getObject(getActivity(), LoginModel.DataBean.class);
        if(userinfoModel!=null){
            uid = userinfoModel.getId();
            token= userinfoModel.getAndroidtoken();
        }
        String mDate = TimeUtil.getNowDateShort();
        Call<BloodYearBean> stepsDayBean = ApiHelper.getBloodLogYear(uid,mDate,token);
        stepsDayBean.enqueue(new Callback<BloodYearBean>() {
            @Override
            public void onResponse(Call<BloodYearBean> call, Response<BloodYearBean> response) {
                BloodYearBean body = response.body();
                if (body == null) return;
                if (body.getCode().equals("0")){
                    bloodList= body.getData();
                    Collections.reverse(bloodList); // 倒序排列
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            initView();
                        }
                    });
                }else{
                }
            }

            @Override
            public void onFailure(Call<BloodYearBean> call, Throwable t) {

                Log.i("tag",t.getMessage());
            }
        });

    }
    private void initView() {
        tv_typeDate.setText(DateUtils.getNowdate());
        List<View> view = new ArrayList<>();
        LayoutInflater lf = getLayoutInflater().from(getActivity());
        if(!bloodList.isEmpty()) {
            for (int i = 0; i < bloodList.size(); i++) {
                View viewDay = lf.inflate(R.layout.item_barchart, null);
                view.add(viewDay);
                barChart = viewDay.findViewById(R.id.barChart);
                BloodYearBean.DataBean model = bloodList.get(i);

                intChart(model,i);

            }

            sumData = bloodList.size();
            pon = sumData;
//            tv_sbp_hight  tv_sbp_low   tv_sbp_avg tv_dbp_hight  tv_dbp_low tv_dbp_avg

//      //下面是四个
            tv_typeDate.setText(bloodList.get(bloodList.size()-1).getName());
            tv_bottom_title.setText("血压状态值(mmHg)");

            tv_sbp_hight.setText(bloodList.get(bloodList.size()-1).getMax_shousuoya());
            tv_sbp_low.setText(bloodList.get(bloodList.size()-1).getMin_shousuoya());
            tv_sbp_avg.setText(bloodList.get(bloodList.size()-1).getAvg_shousuoya());

            tv_dbp_hight.setText(bloodList.get(bloodList.size()-1).getMax_shuzhangya());
            tv_dbp_low.setText(bloodList.get(bloodList.size()-1).getMin_shuzhangya());
            tv_dbp_avg.setText(bloodList.get(bloodList.size()-1).getAvg_shuzhangya());
        }
        MyStepsViewPagerAdapter adapter =new  MyStepsViewPagerAdapter(view);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(sumData);
        viewPager.setOnPageChangeListener(this);
    }

   @OnClick({R.id.btn_left,R.id.btn_right})
   //左右点击选择
   public void checkClick(View v){
       pon = viewPager.getCurrentItem();
       if(v.getId()==R.id.btn_left){
           pon = pon-1;
           if(pon<0){
               return;
           }
           postion = postion-1;
           viewPager.setCurrentItem(pon);


           tv_typeDate.setText(bloodList.get(pon).getName());
           tv_bottom_title.setText("血压状态值(mmHg)");

           tv_sbp_hight.setText(bloodList.get(pon).getMax_shousuoya());
           tv_sbp_low.setText(bloodList.get(pon).getMin_shousuoya());
           tv_sbp_avg.setText(bloodList.get(pon).getAvg_shousuoya());

           tv_dbp_hight.setText(bloodList.get(pon).getMax_shuzhangya());
           tv_dbp_low.setText(bloodList.get(pon).getMin_shuzhangya());
           tv_dbp_avg.setText(bloodList.get(pon).getAvg_shuzhangya());
       }
       if(v.getId()==R.id.btn_right){
           pon = pon+1;
           if(pon>bloodList.size()-1){
               return;
           }
           postion = postion+1;
           viewPager.setCurrentItem(pon);


           tv_typeDate.setText(bloodList.get(pon).getName());
           tv_bottom_title.setText("血压状态值(mmHg)");

           tv_sbp_hight.setText(bloodList.get(pon).getMax_shousuoya());
           tv_sbp_low.setText(bloodList.get(pon).getMin_shousuoya());
           tv_sbp_avg.setText(bloodList.get(pon).getAvg_shousuoya());

           tv_dbp_hight.setText(bloodList.get(pon).getMax_shuzhangya());
           tv_dbp_low.setText(bloodList.get(pon).getMin_shuzhangya());
           tv_dbp_avg.setText(bloodList.get(pon).getAvg_shuzhangya());

       }

   }
    //这是顶部折线统计
    private void intChart(BloodYearBean.DataBean  model,int poi) {



        barChart.animateY(1000, Easing.EasingOption.Linear);
        barChart.animateX(1000, Easing.EasingOption.Linear);
        barChart.setDrawBarShadow(false);
        barChart.setDrawValueAboveBar(true);


        barChart. setVisibleXRange(2f,  10f);


        barChart.getDescription().setEnabled(false);
        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        barChart.setMaxVisibleValueCount(300);

        // scaling can now only be done on x- and y-axis separately
        barChart.setPinchZoom(false);

        barChart.setDrawGridBackground(false);//是否显示网格

        IAxisValueFormatter xAxisFormatter = new DayFormatter();

        XAxis xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f); // only intervals of 1 day
        xAxis.setLabelCount(20);
        xAxis.setValueFormatter(xAxisFormatter);

        IAxisValueFormatter custom = new MyAxisValueFormatter();

        YAxis leftAxis = barChart.getAxisLeft();
        leftAxis.setLabelCount(8, false);
        leftAxis.setValueFormatter(custom);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(15f);
        leftAxis.setDrawGridLines(false);//是否画线
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        leftAxis.setEnabled(false);
        xAxis.setTextSize(10.5f);


        YAxis rightAxis = barChart.getAxisRight();
        rightAxis.setDrawGridLines(false);
        rightAxis.setLabelCount(8, false);
        rightAxis.setValueFormatter(custom);
        rightAxis.setSpaceTop(15f);
        rightAxis.setDrawGridLines(false);//是否画线
        rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        rightAxis.setEnabled(false);


        XYMarkerView mv = new XYMarkerView(getActivity(), new MyAxisValueFormatter());
        mv.setChartView(barChart); // For bounds control
        mv.setEnabled(false);
        Legend l = barChart.getLegend();     //底部显示数据
        l.setForm(Legend.LegendForm.LINE);
//        barChart.setMarker(mv); // Set the marker to the chart

        barChart.setBorderWidth(50f);
        barChart.setEnabled(true);
        setBarChartData(model);

    }


    private void setBarChartData(BloodYearBean.DataBean model) {
        ArrayList<Entry> values = new ArrayList<Entry>();

        ArrayList<BarEntry> values1 = new ArrayList<BarEntry>();
        ArrayList<BarEntry> values2 = new ArrayList<BarEntry>();
        List<BloodYearBean.DataBean.ListBean> tempBloodList  = model.getList();
//        Collections.reverse(tempBloodList); // 倒序排列
        if(tempBloodList.size()>0){
            for (int i = 0; i < tempBloodList.size(); i++) {
                values1.add(new BarEntry(i, Float.valueOf(tempBloodList.get(i).getAvg_shousuoya())));
                values2.add(new BarEntry(i, Float.valueOf(tempBloodList.get(i).getAvg_shuzhangya())));
            }
        }




        BarDataSet set1;  //这就是每个柱状图的实例

        set1 = new BarDataSet(values1, "收缩压");
        set1.setColor(R.color.primarycolor);
        int[] PASTEL_COLORS = {  //设置每个柱状图背景色
                Color.rgb(75, 204, 209)
        };
        set1.setColors(PASTEL_COLORS);
        set1.setDrawIcons(false);



        BarDataSet set2;  //这就是每个柱状图的实例
        set2 = new BarDataSet(values2, "舒张压");
        set2.setColor(R.color.sleepnext);
        set2.setDrawIcons(false);

//        int[] PASTEL_COLORS2 = {  //设置每个柱状图背景色
//                Color.rgb(148, 93, 191)
//        };
//        set2.setColors(PASTEL_COLORS2);

        ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
        dataSets.add(set1);
        dataSets.add(set2);

        BarData data = new BarData(dataSets);
        data.setValueTextSize(10f);//调节顶部字体大小
        data.setValueTextColor(R.color.mainMotion_li);
        data.setBarWidth(0.15f); //调节间距的
        Float valueF1 = set1.getYMax();
        Float valueF2 = set2.getYMax();
        set1.setValueFormatter(new myValueFormatter(valueF1));
        set2.setValueFormatter(new myValueFormatter(valueF2));
        barChart.setData(data);
        barChart.invalidate(); // 重新更新显示
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    //页面滑动后调用
    @Override
    public void onPageSelected(int p) {
        pon = viewPager.getCurrentItem();
        tv_typeDate.setText(bloodList.get(pon).getName());

        tv_bottom_title.setText("血压状态值(mmHg)");
        tv_sbp_hight.setText(bloodList.get(pon).getMax_shousuoya());
        tv_sbp_low.setText(bloodList.get(pon).getMin_shousuoya());
        tv_sbp_avg.setText(bloodList.get(pon).getAvg_shousuoya());

        tv_dbp_hight.setText(bloodList.get(pon).getMax_shuzhangya());
        tv_dbp_low.setText(bloodList.get(pon).getMin_shuzhangya());
        tv_dbp_avg.setText(bloodList.get(pon).getAvg_shuzhangya());
    }
    @Override
    public void onPageScrollStateChanged(int state) {
    }
    //这是设置下端的数值
    class DayFormatter implements IAxisValueFormatter
    {
        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            String appendix="";
            if(value==0.0) {
                appendix = "1";
            }else if(value==1.0){
                appendix = "2";
            }else if(value==2.0){
                appendix = "3";
            }else if(value==3.0){
                appendix = "4";
            }else if(value==4.0){
                appendix = "5";
            }else if(value==5.0){
                appendix = "6";
            }else if(value==6.0){
                appendix = "7";
            }else if(value==7.0){
                appendix = "8";
            }else if(value==8.0){
                appendix = "9";
            }else if(value==9.0){
                appendix = "10";
            }else if(value==10.0){
                appendix = "11";
            }else if(value==11.0){
                appendix = "12";
            }else{
                appendix = "";
            }

            return appendix;
        }

        private int getDaysForMonth(int month, int year) {

            // month is 0-based

            if (month == 1) {
                boolean is29Feb = false;

                if (year < 1582)
                    is29Feb = (year < 1 ? year + 1 : year) % 4 == 0;
                else if (year > 1582)
                    is29Feb = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);

                return is29Feb ? 29 : 28;
            }

            if (month == 3 || month == 5 || month == 8 || month == 10)
                return 30;
            else
                return 31;
        }

        private int determineMonth(int dayOfYear) {

            int month = -1;
            int days = 0;

            while (days < dayOfYear) {
                month = month + 1;

                if (month >= 12)
                    month = 0;

                int year = determineYear(days);
                days += getDaysForMonth(month, year);
            }

            return Math.max(month, 0);
        }

        private int determineDayOfMonth(int days, int month) {

            int count = 0;
            int daysForMonths = 0;

            while (count < month) {

                int year = determineYear(daysForMonths);
                daysForMonths += getDaysForMonth(count % 12, year);
                count++;
            }

            return days - daysForMonths;
        }

        private int determineYear(int days) {

            if (days <= 366)
                return 2016;
            else if (days <= 730)
                return 2017;
            else if (days <= 1094)
                return 2018;
            else if (days <= 1458)
                return 2019;
            else
                return 2020;

        }
    }
    //这是设置上端的显示的最大数值
    class myValueFormatter implements IValueFormatter
    {
        boolean isRest;
        private Float valueF;
        private Float valueX;
        public myValueFormatter(Float valueF){
            this.valueF = valueF;
        }

        @Override
        public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {

            if(!isRest){
                if(valueF==value&&value!=0){
                    valueX= entry.getX();
                    isRest=true;
                    DecimalFormat decimalFormat=new DecimalFormat("#");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                    String str =decimalFormat.format(valueF);//format 返回的是字符串
                    return str;
                }else{
                    return "";
                }
            }else{
                if(valueX==entry.getX()){
                    DecimalFormat decimalFormat=new DecimalFormat("#");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                    String str =decimalFormat.format(valueF);//format 返回的是字符串
                    return str;
                }else{
                    return "";
                }

            }




        }
    }
}
